# encoding: utf-8
# @File  : dun_01_SlideBlock.py
# @Author: wu shaofan
# @Date  :  2024/02/16
# @Desc : 网易网盾滑动块--弹出式（未封装）
import os
import time
import cv2
import requests
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
import conftest

def FindPic(target='big.png', template='small.png'):
    target_rgb = cv2.imread(target)
    target_gray = cv2.cvtColor(target_rgb, cv2.COLOR_RGB2GRAY)
    template_rgb = cv2.imread(template, 0)
    res = cv2.matchTemplate(target_gray, template_rgb, cv2.TM_CCOEFF_NORMED)
    value = cv2.minMaxLoc(res)
    print(value)
    return value[3][0]

chrome_driver_path = conftest.BASE_DIR + '/tool/chromedriver.exe'
# 创建 ChromeOptions 对象
options = Options()
options.add_experimental_option("excludeSwitches", ["enable-logging"])
# 创建 Chrome WebDriver 服务
service = Service(chrome_driver_path)
# 创建 Chrome WebDriver 实例
driver = webdriver.Chrome(service=service, options=options)
# 窗口最大化
driver.maximize_window()
# 打开网页
url = "https://dun.163.com/trial/sense"
# 打开网址
driver.get(url)


# 点击 可疑用户-滑动拼图
loc1 = ('css selector', 'ul[class="tcapt-tabs__container"] li[captcha-type="jigsaw"]')
WebDriverWait(driver, timeout=3, poll_frequency=0.5).until(lambda x: x.find_element(*loc1)).click()

# 滚动页面滑动条，让滑块显示出来
js = 'document.documentElement.scrollTop=200'
driver.execute_script(js)

# 点击完成验证按钮
loc2 = ('css selector', 'span[class="yidun_intelli-text"]')
WebDriverWait(driver, timeout=3, poll_frequency=0.5).until(lambda x: x.find_element(*loc2)).click()

while True:
    '''保存图片'''
    # 小图片
    loc3 = ('class name', 'yidun_jigsaw')
    url_s = WebDriverWait(driver, timeout=3, poll_frequency=0.5).until(lambda x: x.find_element(*loc3)).get_attribute('src')
    # 大图片
    url_b = driver.find_element('class name', 'yidun_bg-img').get_attribute('src')
    header = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36'}
    # 发送请求，获取验证码图片
    response_s = requests.get(url_s, headers=header).content
    response_b = requests.get(url_b, headers=header).content

    # 判断文件夹是否存在不存在则创建'
    os.makedirs('./image/', exist_ok=True)
    # 保存图片
    with open('./image/slider_s.png', 'wb') as f:
        f.write(response_s)
    with open('./image/slider_b.png', 'wb') as f:
        f.write(response_b)


    '''小图在大图中的缺口位置'''
    distance = FindPic('./image/slider_b.png', './image/slider_s.png')
    print("本地图片需要滑动的距离：{}".format(distance))

    # 获取滑块元素
    loc4 = ('css selector', '.yidun_slider.yidun_slider--hover')
    ele =  WebDriverWait(driver, timeout=3, poll_frequency=0.5).until(lambda x: x.find_element(*loc4))

    # 实例化对象
    action = ActionChains(driver)
    # 拖动滑块
    action.drag_and_drop_by_offset(ele, xoffset=distance, yoffset=0).perform()

    # 定位到验证成功
    time.sleep(1)
    loc5 = ('css selector', '.yidun_tips__text.yidun-fallback__tip')
    text = WebDriverWait(driver, timeout=3, poll_frequency=0.5).until(lambda x: x.find_element(*loc5)).text
    if text == "验证成功":
        break
print("验证成功")